<template>
  <div class="user-card" :class="cardClass">
    <!-- 用户头像 -->
    <div class="avatar-container">
      <img
        v-if="user.avatar"
        :src="user.avatar"
        :alt="user.username || user.nickname"
        class="avatar"
        @error="handleAvatarError"
      />
      <div v-else class="avatar-placeholder">
        <span>{{ getInitials() }}</span>
      </div>
      <!-- 在线状态指示器 -->
      <div v-if="showStatus" :class="['status-indicator', `status-${user.status}`]"></div>
    </div>
    
    <!-- 用户信息 -->
    <div class="user-info">
      <div class="name-section">
        <h3 class="username">
          {{ user.username || user.nickname || '未知用户' }}
          <span v-if="user.isVerified" class="verified-badge" title="已认证">
            <el-icon><Check /></el-icon>
          </span>
        </h3>
        <span v-if="user.nickname && user.nickname !== user.username" class="nickname">
          {{ user.nickname }}
        </span>
      </div>
      
      <!-- 用户状态 -->
      <div v-if="showStatus" class="status-text">
          <el-tag :type="getStatusType()" size="small">
            {{ getStatusText() }}
          </el-tag>
        </div>
      
      <!-- 用户详情 -->
      <div v-if="showDetails" class="user-details">
        <div v-if="user.email" class="detail-item">
          <el-icon class="detail-icon"><Message /></el-icon>
          <span class="detail-text">{{ user.email }}</span>
        </div>
        <div v-if="user.phone" class="detail-item">
          <el-icon class="detail-icon"><Phone /></el-icon>
          <span class="detail-text">{{ user.phone }}</span>
        </div>
        <div v-if="user.role" class="detail-item">
          <el-icon class="detail-icon"><UserIcon /></el-icon>
          <span class="detail-text">{{ getRoleText() }}</span>
        </div>
        <div v-if="user.createdAt" class="detail-item">
          <el-icon class="detail-icon"><Calendar /></el-icon>
          <span class="detail-text">{{ formatDate(user.createdAt) }}</span>
        </div>
        <div v-if="user.lastLogin" class="detail-item">
          <el-icon class="detail-icon"><Clock /></el-icon>
          <span class="detail-text">{{ formatDate(user.lastLogin) }}</span>
        </div>
      </div>
      
      <!-- 统计信息 -->
        <div v-if="showStats" class="user-stats">
          <div v-if="user.posts" class="stat-item">
            <span class="stat-number">{{ user.posts }}</span>
            <span class="stat-label">帖子</span>
          </div>
          <div v-if="user.comments" class="stat-item">
            <span class="stat-number">{{ user.comments }}</span>
            <span class="stat-label">评论</span>
          </div>
          <div v-if="user.likes" class="stat-item">
            <span class="stat-number">{{ user.likes }}</span>
            <span class="stat-label">获赞</span>
          </div>
          <div v-if="user.followers" class="stat-item">
            <span class="stat-number">{{ user.followers }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div v-if="user.following" class="stat-item">
            <span class="stat-number">{{ user.following }}</span>
            <span class="stat-label">关注</span>
          </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div v-if="showActions" class="action-buttons">
      <button
        v-if="user.id !== currentUserId"
        :class="['action-btn', `action-${isFollowing ? 'unfollow' : 'follow'}`]"
        @click="handleFollowToggle"
      >
        {{ isFollowing ? '已关注' : '关注' }}
      </button>
      <button
        v-if="user.id !== currentUserId"
        class="action-btn action-message"
        @click="handleMessage"
      >
        发消息
      </button>
      <button
        v-if="showEdit && (user.id === currentUserId || isAdmin)"
        class="action-btn action-edit"
        @click="handleEdit"
      >
        编辑
      </button>
      <button
        v-if="showDelete && isAdmin"
        class="action-btn action-delete"
        @click="handleDelete"
      >
        删除
      </button>
    </div>
    
    <!-- 自定义内容插槽 -->
    <div v-if="$slots.extra" class="extra-content">
      <slot name="extra" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, withDefaults, defineProps, defineEmits } from 'vue'
import type { User } from '../types/user'
import { ElTag, ElIcon } from 'element-plus'
import {
  Check,
  Message,
  Phone,
  User as UserIcon,
  Calendar,
  Clock
} from '@element-plus/icons-vue'
import { formatDate } from '../utils/common'

// 扩展User接口以包含额外的属性
interface ExtendedUser extends User {
  likes?: number
  posts?: number
  comments?: number
  followers?: number
  following?: number
  isVerified?: boolean
}

// Props
interface Props {
  user: Partial<ExtendedUser>
  currentUserId?: string | number
  showActions?: boolean
  showDetails?: boolean
  showStats?: boolean
  showStatus?: boolean
  showEdit?: boolean
  showDelete?: boolean
  isAdmin?: boolean
  isFollowing?: boolean
  size?: 'small' | 'medium' | 'large'
  theme?: 'light' | 'dark' | 'bordered'
}

const props = withDefaults(defineProps<Props>(), {
  user: () => ({}),
  showActions: true,
  showDetails: true,
  showStats: true,
  showStatus: true,
  showEdit: true,
  showDelete: false,
  isAdmin: false,
  isFollowing: false,
  size: 'medium',
  theme: 'light'
})

// Emits
const emit = defineEmits<{
  'follow': [userId: string | number]
  'unfollow': [userId: string | number]
  'message': [userId: string | number]
  'edit': [userId: string | number]
  'delete': [userId: string | number]
}>()

// Refs
const internalIsFollowing = ref(props.isFollowing)

// 计算样式类名
const cardClass = computed(() => {
  return [
    `user-card-${props.size}`,
    `user-card-${props.theme}`
  ]
})

// 获取用户首字母
const getInitials = () => {
  const name = props.user.username || props.user.nickname || ''
  if (!name) return 'U'
  return name.charAt(0).toUpperCase()
}

// 获取状态文本
const getStatusText = () => {
  const statusMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    busy: '忙碌',
    away: '离开'
  }
  return statusMap[props.user.status as string] || '未知'
}

// 获取状态标签类型
const getStatusType = (): "primary" | "success" | "warning" | "info" | "danger" => {
  const typeMap: Record<string, "primary" | "success" | "warning" | "info" | "danger"> = {
    online: 'success',
    offline: 'info',
    busy: 'danger',
    away: 'warning'
  }
  return typeMap[props.user.status as string] || 'info'
}

// 获取角色文本
const getRoleText = () => {
  const roleMap: Record<string, string> = {
    admin: '管理员',
    moderator: '版主',
    user: '普通用户',
    guest: '访客'
  }
  return roleMap[props.user.role as string] || '未知角色'
}

// 处理头像加载错误
const handleAvatarError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.style.display = 'none'
}

// 处理关注/取消关注
const handleFollowToggle = () => {
  if (!props.user.id) return
  
  if (internalIsFollowing.value) {
    emit('unfollow', props.user.id)
  } else {
    emit('follow', props.user.id)
  }
  internalIsFollowing.value = !internalIsFollowing.value
}

// 处理发消息
const handleMessage = () => {
  if (props.user.id) {
    emit('message', props.user.id)
  }
}

// 处理编辑
const handleEdit = () => {
  if (props.user.id) {
    emit('edit', props.user.id)
  }
}

// 处理删除
const handleDelete = () => {
  if (props.user.id) {
    emit('delete', props.user.id)
  }
}

// 暴露方法
defineExpose({
  toggleFollow: handleFollowToggle,
  openMessage: handleMessage,
  openEdit: handleEdit,
  triggerDelete: handleDelete
})
</script>

<style scoped>
.user-card {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

/* 主题样式 */
.user-card-light {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: none;
}

.user-card-dark {
  background-color: #1f2937;
  color: #f3f4f6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  border: none;
}

.user-card-bordered {
  background-color: #fff;
  border: 1px solid #e5e7eb;
  box-shadow: none;
}

/* 尺寸样式 */
.user-card-small {
  padding: 12px;
}

.user-card-medium {
  padding: 16px;
}

.user-card-large {
  padding: 20px;
}

/* 头像区域 */
.avatar-container {
  position: relative;
  display: flex;
  justify-content: center;
  margin-bottom: 12px;
}

.avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e7eb;
}

.avatar-placeholder {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background-color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: 600;
  border: 2px solid #e5e7eb;
}

.user-card-small .avatar,
.user-card-small .avatar-placeholder {
  width: 48px;
  height: 48px;
  font-size: 20px;
}

.user-card-large .avatar,
.user-card-large .avatar-placeholder {
  width: 80px;
  height: 80px;
  font-size: 28px;
}

/* 在线状态指示器 */
.status-indicator {
  position: absolute;
  bottom: 0;
  right: calc(50% - 32px);
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid #fff;
  background-color: #9ca3af;
}

.user-card-dark .status-indicator {
  border-color: #1f2937;
}

.status-online {
  background-color: #10b981;
}

.status-offline {
  background-color: #9ca3af;
}

.status-busy {
  background-color: #ef4444;
}

.status-away {
  background-color: #f59e0b;
}

.user-card-small .status-indicator {
  width: 12px;
  height: 12px;
  right: calc(50% - 24px);
}

.user-card-large .status-indicator {
  width: 20px;
  height: 20px;
  right: calc(50% - 40px);
}

/* 用户信息 */
.user-info {
  text-align: center;
  margin-bottom: 16px;
}

.name-section {
  margin-bottom: 8px;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.user-card-dark .username {
  color: #f3f4f6;
}

.verified-badge {
  color: #409eff;
  font-size: 16px;
}

.nickname {
  font-size: 14px;
  color: #6b7280;
}

.user-card-dark .nickname {
  color: #9ca3af;
}

.status-text {
  margin-bottom: 8px;
}

/* 用户详情 */
.user-details {
  margin-top: 12px;
  font-size: 14px;
}

.detail-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin-bottom: 6px;
  color: #6b7280;
}

.user-card-dark .detail-item {
  color: #9ca3af;
}

.detail-icon {
  font-size: 14px;
}

/* 统计信息 */
.user-stats {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
}

.user-card-dark .user-stats {
  border-top-color: #374151;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.user-card-dark .stat-number {
  color: #f3f4f6;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #6b7280;
}

.user-card-dark .stat-label {
  color: #9ca3af;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background-color: #fff;
  color: #374151;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-card-dark .action-btn {
  background-color: #374151;
  color: #f3f4f6;
  border-color: #4b5563;
}

.action-btn:hover {
  background-color: #f3f4f6;
  border-color: #9ca3af;
}

.user-card-dark .action-btn:hover {
  background-color: #4b5563;
  border-color: #6b7280;
}

.action-follow {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.action-follow:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

.action-unfollow {
  background-color: #f3f4f6;
  color: #374151;
  border-color: #d1d5db;
}

.action-unfollow:hover {
  background-color: #e5e7eb;
  border-color: #9ca3af;
  color: #374151;
}

.user-card-dark .action-unfollow {
  background-color: #6b7280;
  color: #f3f4f6;
  border-color: #4b5563;
}

.user-card-dark .action-unfollow:hover {
  background-color: #9ca3af;
  border-color: #6b7280;
}

.action-message {
  background-color: #67c23a;
  color: white;
  border-color: #67c23a;
}

.action-message:hover {
  background-color: #85ce61;
  border-color: #85ce61;
  color: white;
}

.action-edit {
  background-color: #e6a23c;
  color: white;
  border-color: #e6a23c;
}

.action-edit:hover {
  background-color: #ebb563;
  border-color: #ebb563;
  color: white;
}

.action-delete {
  background-color: #f56c6c;
  color: white;
  border-color: #f56c6c;
}

.action-delete:hover {
  background-color: #f78989;
  border-color: #f78989;
  color: white;
}

/* 自定义内容 */
.extra-content {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

.user-card-dark .extra-content {
  border-top-color: #374151;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .user-card {
    padding: 12px;
  }
  
  .user-stats {
    gap: 12px;
  }
  
  .action-buttons {
    gap: 6px;
  }
  
  .action-btn {
    padding: 5px 10px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .user-card {
    padding: 10px;
  }
  
  .username {
    font-size: 16px;
  }
  
  .stat-number {
    font-size: 14px;
  }
  
  .stat-label {
    font-size: 11px;
  }
}
</style>